/*
 * 命令行
 * @author li.xiaomei
 */

var optimist = require('optimist'),
  syspath = require('path'),
  fs = require('fs'),
  utillogger = require('./utils/logger'),
  pkg = require('../package.json');

global.configName = 'rightfe';

//command 对应commands里面的每一个命令文件 eg: server.js
var init_options = function(command) {
  var cwd, opts, options;

  if (command.set_options) {
    opts = command.set_options(optimist);
  } else {
    opts = optimist;
  }

  opts.alias('h', 'help');
  opts.describe('h', '查看帮助');
  options = opts.argv;
  cwd = process.cwd();
  options.cwd = cwd;

  return options;
};

var title = function() {
  console.info('');
  //加大图

  console.log('============ rightFe ' + pkg.version + '============');
};

exports.help = function() {
  title();
  console.info("");
  console.info(" 如果需要帮助, 请使用 rightfe {命令名} --help ");
  return console.info("");
};

var find_cmd = function(cmd) {
  var lib = syspath.dirname(__filename);
  var path = syspath.join(lib, './commands/' + cmd + '.js');

  if (fs.existsSync(path)) {
    return path;
  }
};

var command_help = function(cmdname, cmd, options) {
  title();
  console.info('命令：' + cmdname + ' ');
  console.log('功能：' + cmd.usage + ' ');
  console.log('');
  return optimist.showHelp();
};

var command_run = function(cmdname, cmd, options) {
  return cmd.run(options);
};

exports.run = function(cmd) {
  var command, options, path;
  path = find_cmd(cmd);
  if (!path) {
    utillogger.error('请确认是否有' + cmd + ' 这个命令');
    return 1;
  }

  utillogger.trace('加载命令' + path);
  command = require(path);
  options = init_options(command);

  if (options.help) {
    command_help(cmd, command, options);
  } else {
    command_run(cmd, command, options);
  }
};
